const express = require('express');
const router = express.Router();
const mysql = require('mysql2');

// 数据库连接
const connection = mysql.createConnection({
  host: '10.11.5.167',
  port: 13306,
  user: 'root',
  password: '123456',
  database: 'my_database'
});

// 生成随机账号
function generateAccount() {
  const length = Math.floor(Math.random() * 4) + 6; // 6-9位
  let account = '';
  for (let i = 0; i < length; i++) {
    account += Math.floor(Math.random() * 10);
  }
  return account;
}

// 注册接口
router.post('/register', (req, res) => {
  const { username, password } = req.body;
  if (!username || !password) {
    return res.status(400).json({ success: false, message: '缺少必要的注册参数' });
  }

  // 查重
  connection.query(
    'SELECT * FROM users WHERE username = ?',
    [username],
    (err, results) => {
      if (err) {
        return res.status(500).json({ success: false, message: '数据库错误', error: err.message });
      }
      if (results.length > 0) {
        return res.status(400).json({ success: false, message: '用户名已存在' });
      }

      // 生成唯一账号
      function insertUserWithUniqueAccount() {
        const account = generateAccount();
        connection.query(
          'SELECT * FROM users WHERE account = ?',
          [account],
          (err, accResults) => {
            if (err) {
              return res.status(500).json({ success: false, message: '数据库错误', error: err.message });
            }
            if (accResults.length > 0) {
              // 账号重复，重新生成
              insertUserWithUniqueAccount();
            } else {
              // 插入新用户
              connection.query(
                'INSERT INTO users (username, password, account) VALUES (?, ?, ?)',
                [username, password, account],
                (err, result) => {
                  if (err) {
                    return res.status(500).json({ success: false, message: '注册失败', error: err.message });
                  }
                  res.json({ success: true, message: '注册成功', user: { username, account } });
                }
              );
            }
          }
        );
      }
      insertUserWithUniqueAccount();
    }
  );
});

// 登录接口
router.post('/login', (req, res) => {
  const { account, password } = req.body;
  if (!account || !password) {
    return res.status(400).json({ success: false, message: '缺少必要的登录参数' });
  }
  connection.query(
    'SELECT * FROM users WHERE account = ? AND password = ?',
    [account, password],
    (err, results) => {
      if (err) {
        return res.status(500).json({ success: false, message: '数据库错误', error: err.message });
      }
      if (results.length === 0) {
        return res.status(401).json({ success: false, message: '账号或密码错误' });
      }
      // 登录成功，返回用户信息
      const user = results[0];
      res.json({ success: true, message: '登录成功', user: { username: user.username, account: user.account } });
    }
  );
});

module.exports = router;
